﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace K9Nano.Security
{
    public static class Md5Helper
    {
        /// <summary>
        /// 计算Hash
        /// </summary>
        /// <returns></returns>
        public static string ComputeHash(string text, Encoding encoding)
        {
            using var md5 = new MD5CryptoServiceProvider();
            byte[] bytes = encoding.GetBytes(text);
            string result = BitConverter.ToString(md5.ComputeHash(bytes));
            return result.Replace("-", "");
        }

        /// <summary>
        /// 使用UTF8计算Hash
        /// </summary>
        /// <returns></returns>
        public static string ComputeHash(string text) => ComputeHash(text, Encoding.UTF8);

        public static bool Validate(string text, string hash)
        {
            return string.CompareOrdinal(ComputeHash(text), hash) == 0;
        }

        public static bool Validate(string text, string hash, Encoding encoding)
        {
            return string.CompareOrdinal(ComputeHash(text, encoding), hash) == 0;
        }
    }
}